package api

import (
	"aigen-todo/internal/models"
	"aigen-todo/internal/service"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// CreateTaskRequest defines the structure for creating a task
type CreateTaskRequest struct {
	// Group ID for the task
	// required: true
	// example: 1
	GroupID uint64 `json:"group_id" binding:"required"`

	// Title of the task
	// required: true
	// example: 完成项目报告
	Title string `json:"title" binding:"required"`

	// Description of the task
	// example: 编写并提交季度项目报告
	Description string `json:"description"`

	// Whether the task is important
	// example: true
	IsImportant bool `json:"is_important"`

	// Whether the task is in "My Day"
	// example: false
	IsMyDay bool `json:"is_my_day"`

	// Due date for the task (format: YYYY-MM-DD)
	// example: 2025-12-31
	DueDate string `json:"due_date"`
}

// UpdateTaskRequest defines the structure for updating a task
type UpdateTaskRequest struct {
	// Group ID for the task
	// example: 1
	GroupID *uint64 `json:"group_id"`

	// Title of the task
	// example: 更新项目报告
	Title *string `json:"title"`

	// Description of the task
	// example: 更新并提交季度项目报告
	Description *string `json:"description"`

	// Whether the task is important
	// example: true
	IsImportant *bool `json:"is_important"`

	// Whether the task is in "My Day"
	// example: true
	IsMyDay *bool `json:"is_my_day"`

	// Status of the task (0: New, 1: In Progress, 2: Completed)
	// example: 1
	Status *int `json:"status"`

	// Due date for the task (format: YYYY-MM-DD)
	// example: 2025-12-31
	DueDate *string `json:"due_date"`
}

// ChangeTaskGroupRequest defines the structure for changing task group
type ChangeTaskGroupRequest struct {
	// Group ID to move the task to
	// required: true
	// example: 2
	GroupID uint64 `json:"group_id" binding:"required"`
}

// TaskItem defines the structure for a task item
type TaskItem struct {
	TaskID      uint64     `json:"task_id"`
	GroupID     uint64     `json:"group_id"`
	Title       string     `json:"title"`
	Description string     `json:"description"`
	IsImportant bool       `json:"is_important"`
	IsMyDay     bool       `json:"is_my_day"`
	Status      int        `json:"status"`
	DueDate     *time.Time `json:"due_date"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   *time.Time `json:"updated_at,omitempty"`
}

// CreateTaskHandler godoc
// @Summary      创建任务
// @Description  创建一个新的任务
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        createTaskReq body CreateTaskRequest true "创建任务请求"
// @Success      200  {object}  TaskResponse
// @Failure      400  {object}  TaskResponse
// @Failure      401  {object}  TaskResponse
// @Failure      500  {object}  TaskResponse
// @Router       /tasks [post]
func CreateTaskHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		var req CreateTaskRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		// 解析截止日期
		var dueDate *time.Time
		if req.DueDate != "" {
			parsedDate, err := time.Parse("2006-01-02", req.DueDate)
			if err != nil {
				BadRequest(c, "截止日期格式错误") // 自定义错误消息
				return
			}
			dueDate = &parsedDate
		}

		task, err := taskService.CreateTask(
			userID.(uint64),
			req.GroupID,
			req.Title,
			req.Description,
			req.IsImportant,
			req.IsMyDay,
			dueDate,
		)
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		data := map[string]interface{}{
			"task_id":      task.ID,
			"group_id":     task.GroupID,
			"title":        task.Title,
			"description":  task.Description,
			"is_important": task.IsImportant,
			"is_my_day":    task.IsMyDay,
			"status":       task.Status,
			"due_date":     task.DueDate,
			"created_at":   task.CreatedAt,
		}
		SuccessWithMessage(c, "创建成功", data)
	}
}

// GetTaskHandler godoc
// @Summary      获取任务详情
// @Description  获取指定任务的详细信息
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        id path int true "任务ID"
// @Success      200  {object}  TaskResponse
// @Failure      400  {object}  TaskResponse
// @Failure      401  {object}  TaskResponse
// @Failure      403  {object}  TaskResponse
// @Failure      404  {object}  TaskResponse
// @Router       /tasks/{id} [get]
func GetTaskHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		// 获取任务ID
		taskID, err := strconv.ParseUint(c.Param("id"), 10, 64)
		if err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		task, err := taskService.GetTaskByID(taskID)
		if err != nil {
			NotFound(c) // 使用默认错误消息
			return
		}

		// 检查任务是否属于当前用户
		if task.UserID != userID.(uint64) {
			Forbidden(c) // 使用默认错误消息
			return
		}

		data := map[string]interface{}{
			"task_id":      task.ID,
			"group_id":     task.GroupID,
			"title":        task.Title,
			"description":  task.Description,
			"is_important": task.IsImportant,
			"is_my_day":    task.IsMyDay,
			"status":       task.Status,
			"due_date":     task.DueDate,
			"created_at":   task.CreatedAt,
			"updated_at":   task.UpdatedAt,
		}
		SuccessWithMessage(c, "获取成功", data)
	}
}

// GetTasksHandler godoc
// @Summary      获取任务列表
// @Description  获取当前用户的所有任务，支持筛选
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        group_id query int false "分组ID"
// @Param        status query int false "任务状态 (0: 新建, 1: 进行中, 2: 已完成)"
// @Param        is_important query bool false "是否重要任务"
// @Param        is_my_day query bool false "是否我的一天任务"
// @Success      200  {object}  TaskListResponse
// @Failure      401  {object}  TaskListResponse
// @Failure      500  {object}  TaskListResponse
// @Router       /tasks [get]
func GetTasksHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		// 获取查询参数
		groupIDStr := c.Query("group_id")
		statusStr := c.Query("status")
		isImportantStr := c.Query("is_important")
		isMyDayStr := c.Query("is_my_day")

		// 获取所有任务
		tasks, err := taskService.GetTasksByUserID(userID.(uint64))
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		// 根据查询参数过滤任务
		filteredTasks := make([]models.Task, 0)
		for _, task := range tasks {
			// 根据分组ID过滤
			if groupIDStr != "" {
				groupID, err := strconv.ParseUint(groupIDStr, 10, 64)
				if err != nil || task.GroupID != groupID {
					continue
				}
			}

			// 根据状态过滤
			if statusStr != "" {
				status, err := strconv.Atoi(statusStr)
				if err != nil || int(task.Status) != status {
					continue
				}
			}

			// 根据重要性过滤
			if isImportantStr != "" {
				isImportant, err := strconv.ParseBool(isImportantStr)
				if err != nil || task.IsImportant != isImportant {
					continue
				}
			}

			// 根据"我的一天"过滤
			if isMyDayStr != "" {
				isMyDay, err := strconv.ParseBool(isMyDayStr)
				if err != nil || task.IsMyDay != isMyDay {
					continue
				}
			}

			filteredTasks = append(filteredTasks, task)
		}

		// 转换为响应格式
		taskList := make([]map[string]interface{}, len(filteredTasks))
		for i, task := range filteredTasks {
			taskList[i] = map[string]interface{}{
				"task_id":      task.ID,
				"group_id":     task.GroupID,
				"title":        task.Title,
				"description":  task.Description,
				"is_important": task.IsImportant,
				"is_my_day":    task.IsMyDay,
				"status":       task.Status,
				"due_date":     task.DueDate,
				"created_at":   task.CreatedAt,
			}
		}

		data := map[string]interface{}{
			"list": taskList,
		}
		SuccessWithMessage(c, "获取成功", data)
	}
}

// GetMyDayTasksHandler godoc
// @Summary      获取"我的一天"任务列表
// @Description  获取当前用户标记为"我的一天"的所有任务
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Success      200  {object}  TaskListResponse
// @Failure      401  {object}  TaskListResponse
// @Failure      500  {object}  TaskListResponse
// @Router       /tasks/my-day [get]
func GetMyDayTasksHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		tasks, err := taskService.GetMyDayTasks(userID.(uint64))
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		// 转换为响应格式
		taskList := make([]map[string]interface{}, len(tasks))
		for i, task := range tasks {
			taskList[i] = map[string]interface{}{
				"task_id":      task.ID,
				"group_id":     task.GroupID,
				"title":        task.Title,
				"description":  task.Description,
				"is_important": task.IsImportant,
				"status":       task.Status,
				"due_date":     task.DueDate,
				"created_at":   task.CreatedAt,
			}
		}

		data := map[string]interface{}{
			"list": taskList,
		}
		SuccessWithMessage(c, "获取成功", data)
	}
}

// UpdateTaskHandler godoc
// @Summary      更新任务
// @Description  更新指定任务的信息
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        id path int true "任务ID"
// @Param        updateTaskReq body UpdateTaskRequest true "更新任务请求"
// @Success      200  {object}  TaskResponse
// @Failure      400  {object}  TaskResponse
// @Failure      401  {object}  TaskResponse
// @Failure      403  {object}  TaskResponse
// @Failure      404  {object}  TaskResponse
// @Failure      500  {object}  TaskResponse
// @Router       /tasks/{id} [put]
func UpdateTaskHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		// 获取任务ID
		taskID, err := strconv.ParseUint(c.Param("id"), 10, 64)
		if err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		var req UpdateTaskRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		// 获取任务信息
		task, err := taskService.GetTaskByID(taskID)
		if err != nil {
			NotFound(c) // 使用默认错误消息
			return
		}

		// 检查任务是否属于当前用户
		if task.UserID != userID.(uint64) {
			Forbidden(c) // 使用默认错误消息
			return
		}

		// 更新任务
		if req.GroupID != nil {
			task.GroupID = *req.GroupID
		}
		if req.Title != nil {
			task.Title = *req.Title
		}
		if req.Description != nil {
			task.Description = *req.Description
		}
		if req.IsImportant != nil {
			task.IsImportant = *req.IsImportant
		}
		if req.IsMyDay != nil {
			task.IsMyDay = *req.IsMyDay
		}
		if req.Status != nil {
			task.Status = models.TaskStatus(*req.Status)
		}
		if req.DueDate != nil {
			if *req.DueDate != "" {
				parsedDate, err := time.Parse("2006-01-02", *req.DueDate)
				if err != nil {
					BadRequest(c, "截止日期格式错误") // 自定义错误消息
					return
				}
				task.DueDate = &parsedDate
			} else {
				task.DueDate = nil
			}
		}

		err = taskService.UpdateTask(task)
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		data := map[string]interface{}{
			"task_id":      task.ID,
			"group_id":     task.GroupID,
			"title":        task.Title,
			"description":  task.Description,
			"is_important": task.IsImportant,
			"is_my_day":    task.IsMyDay,
			"status":       task.Status,
			"due_date":     task.DueDate,
			"updated_at":   task.UpdatedAt,
		}
		SuccessWithMessage(c, "更新成功", data)
	}
}

// DeleteTaskHandler godoc
// @Summary      删除任务
// @Description  删除指定的任务
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        id path int true "任务ID"
// @Success      200  {object}  TaskResponse
// @Failure      400  {object}  TaskResponse
// @Failure      401  {object}  TaskResponse
// @Failure      403  {object}  TaskResponse
// @Failure      404  {object}  TaskResponse
// @Failure      500  {object}  TaskResponse
// @Router       /tasks/{id} [delete]
func DeleteTaskHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		// 获取任务ID
		taskID, err := strconv.ParseUint(c.Param("id"), 10, 64)
		if err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		// 获取任务信息
		task, err := taskService.GetTaskByID(taskID)
		if err != nil {
			NotFound(c) // 使用默认错误消息
			return
		}

		// 检查任务是否属于当前用户
		if task.UserID != userID.(uint64) {
			Forbidden(c) // 使用默认错误消息
			return
		}

		// 删除任务
		err = taskService.DeleteTask(taskID)
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		SuccessWithMessage(c, "删除成功", nil)
	}
}

// ChangeTaskGroupHandler godoc
// @Summary      更改任务分组
// @Description  将任务移动到另一个分组
// @Tags         任务
// @Accept       json
// @Produce      json
// @Param        Authorization header string true "Bearer Token"
// @Param        id path int true "任务ID"
// @Param        changeTaskGroupReq body ChangeTaskGroupRequest true "更改任务分组请求"
// @Success      200  {object}  TaskResponse
// @Failure      400  {object}  TaskResponse
// @Failure      401  {object}  TaskResponse
// @Failure      403  {object}  TaskResponse
// @Failure      404  {object}  TaskResponse
// @Failure      500  {object}  TaskResponse
// @Router       /tasks/{id}/group [put]
func ChangeTaskGroupHandler(taskService *service.TaskService) gin.HandlerFunc {
	return func(c *gin.Context) {
		userID, exists := c.Get("user_id")
		if !exists {
			Unauthorized(c) // 使用默认错误消息
			return
		}

		// 获取任务ID
		taskID, err := strconv.ParseUint(c.Param("id"), 10, 64)
		if err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		var req ChangeTaskGroupRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			BadRequest(c) // 使用默认错误消息
			return
		}

		// 获取任务信息
		task, err := taskService.GetTaskByID(taskID)
		if err != nil {
			NotFound(c) // 使用默认错误消息
			return
		}

		// 检查任务是否属于当前用户
		if task.UserID != userID.(uint64) {
			Forbidden(c) // 使用默认错误消息
			return
		}

		// 更改任务分组
		err = taskService.ChangeTaskGroup(taskID, req.GroupID)
		if err != nil {
			InternalServerError(c) // 使用默认错误消息
			return
		}

		data := map[string]interface{}{
			"task_id":    taskID,
			"group_id":   req.GroupID,
			"updated_at": time.Now(),
		}
		SuccessWithMessage(c, "更新成功", data)
	}
}
